package com.alibaba.sdk.model;

import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @ author  Shawn(Shawn_0217@163.com)
 * @ date    2021/5/6 11:01
 * @ company Alibaba
 */
@Order(0)
@RestControllerAdvice
public class ApiResponseAdvice implements ResponseBodyAdvice {


    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return returnType.hasMethodAnnotation(ResponseBody.class) ||
                AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ResponseBody.class) ||
                (returnType.getMethod().getReturnType() != Void.TYPE);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if ((selectedContentType.includes(MediaType.APPLICATION_JSON) || selectedContentType.includes(MediaType.APPLICATION_JSON_UTF8))
                && (
                !request.getURI().getPath().startsWith("/swagger") &&
                        !request.getURI().getPath().startsWith("/webjar") &&
                        !request.getURI().getPath().startsWith("/v2/api-docs")
        )

        ) {
            if (body != null && body instanceof OperationResult) {
                return body;
            }
            return new OperationResult<>(body);
        }
        return body;
    }
}
